package com.ruoyi.business.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.ruoyi.business.domain.CarPackageAudit;
import com.ruoyi.business.domain.ServiceItem;
import com.ruoyi.business.mapper.CarPackageAuditMapper;
import com.ruoyi.business.service.ICarPackageAuditService;
import com.ruoyi.business.service.IDefinitionNodeService;
import com.ruoyi.business.service.IProcessService;
import com.ruoyi.business.service.IServiceItemService;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ShiroUtils;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 审核列表Service业务层处理
 * 
 * @author wolfcode
 * @date 2021-07-22
 */
@Service
public class CarPackageAuditServiceImpl implements ICarPackageAuditService
{
    @Autowired
    private CarPackageAuditMapper carPackageAuditMapper;
    @Autowired
    private IProcessService processService;
    @Autowired
    private IServiceItemService serviceItemService;
    @Autowired
    private IDefinitionNodeService definitionNodeService;
    /**
     * 查询审核列表
     *
     * @param id 审核列表ID
     * @return 审核列表
     */
    @Override
    public CarPackageAudit selectCarPackageAuditById(Long id)
    {
        return carPackageAuditMapper.selectCarPackageAuditById(id);
    }

    /**
     * 查询审核列表列表
     *
     * @param carPackageAudit 审核列表
     * @return 审核列表
     */
    @Override
    public List<CarPackageAudit> selectCarPackageAuditList(CarPackageAudit carPackageAudit)
    {
        carPackageAudit.setCreateBy(ShiroUtils.getUserId().toString());
        List<CarPackageAudit> carPackageAudits = carPackageAuditMapper.selectCarPackageAuditList(carPackageAudit);
        for (CarPackageAudit audit:carPackageAudits){
            audit.setServiceItem(JSON.parseObject(audit.getServiceItemInfo(), ServiceItem.class));
            //根据数据中的流程实例id查询任务名称
            Task currentTask = processService.getTaskByProcessInstanceId(audit.getInstanceId());
            if (currentTask!=null){
                audit.setTaskId(currentTask.getId());
                audit.setTaskName(currentTask.getName());
            }else {
                audit.setTaskName("任务结束");
            }
        }
        return carPackageAudits;
    }

    /**
     * 新增审核列表
     *
     * @param carPackageAudit 审核列表
     * @return 结果
     */
    @Override
    public int insertCarPackageAudit(CarPackageAudit carPackageAudit)
    {
        carPackageAudit.setCreateTime(DateUtils.getNowDate());
        return carPackageAuditMapper.insertCarPackageAudit(carPackageAudit);
    }

    /**
     * 修改审核列表
     *
     * @param carPackageAudit 审核列表
     * @return 结果
     */
    @Override
    public int updateCarPackageAudit(CarPackageAudit carPackageAudit)
    {
        return carPackageAuditMapper.updateCarPackageAudit(carPackageAudit);
    }

    /**
     * 删除审核列表对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteCarPackageAuditByIds(String ids)
    {
        return carPackageAuditMapper.deleteCarPackageAuditByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除审核列表信息
     *
     * @param id 审核列表ID
     * @return 结果
     */
    @Override
    public int deleteCarPackageAuditById(Long id)
    {
        return carPackageAuditMapper.deleteCarPackageAuditById(id);
    }

    @Override
    @Transactional
    public void cancelApply(String instanceId, Long carPackageAuditId) {
        //1.把快照表的信息状态修改撤销,审核人设置为空
        CarPackageAudit audit = carPackageAuditMapper.selectCarPackageAuditById(carPackageAuditId);
        audit.setStatus(CarPackageAudit.STATUS_CANCEL);
        audit.setAuditors("");
        carPackageAuditMapper.updateCarPackageAudit(audit);
        //2.把服务项的状态修改为初始化
        ServiceItem item = JSON.parseObject(audit.getServiceItemInfo(),ServiceItem.class);
        item.setAuditStatus(ServiceItem.AUDITSTATUS_INIT);//状态修改为初始化
        serviceItemService.updateServiceItemNoCondition(item);//重写方法,之前的方法会判断状态,如果处于审核中是不允许被修改的
        //3.删除程序
        processService.deleteProcessInstance(instanceId);
    }

    @Override
    public List<CarPackageAudit> selectTodoList(CarPackageAudit carPackageAudit) {
        //获取到当前登录用的ID,根据用户Id查询待办任务
        String userId = ShiroUtils.getUserId().toString();
        //查询符合条件的记录有多少条
        Long count = processService.getTodoTsaskCount(CarPackageAudit.DEFINITION_KEY,userId);
        if (count>0){
            PageDomain pageDomain = TableSupport.buildPageRequest();
            Integer pageNum = pageDomain.getPageNum();
            Integer pageSize = pageDomain.getPageSize();
            Integer starNum=(pageNum-1)*pageSize;
         List<Task> taskList= processService.selectTodoTaskList(
                 CarPackageAudit.DEFINITION_KEY,
                 userId,
                 starNum,
                 pageSize);
         List<CarPackageAudit> resultList = new ArrayList();
         for (Task task:taskList){
          ProcessInstance instance= processService.getProcessInstanceById(task.getProcessInstanceId());
          String businessKey = instance.getBusinessKey();
          CarPackageAudit audit = carPackageAuditMapper.selectCarPackageAuditById(Long.parseLong(businessKey));
          audit.setServiceItem(JSON.parseObject(audit.getServiceItemInfo(),ServiceItem.class));
          audit.setTaskId(task.getId());
          audit.setTaskName(task.getName());
          resultList.add(audit);
         }
         Page page = new Page();
         page.setTotal(count);
         page.setPageNum(pageNum);
         page.setPageSize(pageSize);
         page.addAll(resultList);
            return page;
        }else{

            return Collections.EMPTY_LIST;
        }
    }

    @Override
    @Transactional
    public void complete(String taskId, Boolean auditStatus, String comment) {

        //1.根据任务Id查询任务对象
        Task task = processService.getTaskByTaskId(taskId);
        ProcessInstance processInstance = processService.getProcessInstanceById(task.getProcessInstanceId());
        String businessKey= processInstance.getBusinessKey();

        //这步需要放在前面
        // 3.添加批注,设置流程变量,领取任务,完成任务
        processService.claimAndComplete(task,ShiroUtils.getUserId().toString(),auditStatus,comment);

        //4.完成任务后查询流程实例的下一个任务.
        Task nextTask = processService.getTaskByProcessInstanceId(task.getProcessInstanceId());
        CarPackageAudit audit = carPackageAuditMapper.selectCarPackageAuditById(Long.parseLong(businessKey));

        //5.判断流程是否已经结束
        if(nextTask==null){
            audit.setStatus(CarPackageAudit.STATUS_PASS);
            audit.setAuditors("");
            //更新服务项
            ServiceItem item = JSON.parseObject(audit.getServiceItemInfo(),ServiceItem.class);
            item.setAuditStatus(ServiceItem.AUDITSTATUS_APPROVED);
            serviceItemService.updateServiceItemNoCondition(item);
        }else{
            if (auditStatus){
                List<String> userNameList = new ArrayList<>();
                String taskDefinitionKey = nextTask.getTaskDefinitionKey();
                List<SysUser> auditors = definitionNodeService.queryByTaskDefinitionKey(taskDefinitionKey);
                for (SysUser user:auditors){
                    processService.addCandidateUser(nextTask,user.getUserId());
                    userNameList.add(user.getUserName());
                }
                audit.setAuditors(JSON.toJSONString(userNameList));
            }else{
                processService.addCandidateUser(nextTask,Long.parseLong(audit.getCreateBy()));
                audit.setAuditors(audit.getCreateByName());
                audit.setStatus(CarPackageAudit.STATUS_REJECT);
            }
        }
        carPackageAuditMapper.updateCarPackageAudit(audit);
    }

    @Override
    @Transactional
    public void serviceItemsUpdate(Long carPackageAuditId, ServiceItem serviceItem) {
        serviceItemService.updateServiceItemNoCondition(serviceItem);
        CarPackageAudit audit = carPackageAuditMapper.selectCarPackageAuditById(carPackageAuditId);
        audit.setServiceItemInfo(JSON.toJSONString(serviceItem));
        carPackageAuditMapper.updateCarPackageAudit(audit);
    }
}
